package com.ruoyi.web.controller.laiqianba.Index;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.account.service.IAccountMerchantInfoHisService;
import com.ruoyi.account.service.impl.DailyKpiInfoServiceImpl;
import com.ruoyi.account.service.impl.MonthlyKpiServiceImpl;
import com.ruoyi.channel.service.IChannelCountInfoService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.db.domain.*;
import com.ruoyi.member.service.IMemberBaseInfoService;
import com.ruoyi.member.service.IMemberSourceInfoService;
import com.ruoyi.merchant.service.IMerchantDataPushInfoService;
import com.ruoyi.merchantdata.service.IMerchantDataPoolInfoService;
import com.ruoyi.product.service.IProductProfitInfoService;
import com.ruoyi.source.service.ISourceDataCountInfoService;
import com.ruoyi.source.service.ISourcePushResultInfoService;
import com.ruoyi.web.wrapper.AccountMerchantInfoHisWrapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;


@RestController
@RequestMapping("/index/data")
public class IndexController {

    @Autowired
    private IMemberSourceInfoService memberSourceInfoService;

    @Autowired
    private IAccountMerchantInfoHisService accountMerchantInfoHisService;

    @Autowired
    private IMerchantDataPoolInfoService merchantDataPoolInfoService;

    @Autowired
    private IMerchantDataPushInfoService merchantDataPushInfoService;

    @Autowired
    private ISourceDataCountInfoService sourceDataCountInfoService;

    @Autowired
    private ISourcePushResultInfoService sourcePushResultInfoService;

    @Autowired
    private DailyKpiInfoServiceImpl dailyKpiInfoService;


    @Autowired
    private MonthlyKpiServiceImpl monthlyKpiService;
    @Autowired
    private IProductProfitInfoService  productProfitInfoService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;


    /**
     * 查询 芝麻分数
     */
    @PreAuthorize("@ss.hasPermi('index:data:zhiMa')")
    @GetMapping(value = "/sortZhima")
    public AjaxResult list(@RequestParam("startDate") String startDate,
                           @RequestParam("endDate") String endDate) {
//        String endDateInfo = LocalDate.now().toString();
//        Integer beforeDay = 0;
//        if (type == 1) {
//            endDateInfo = LocalDate.now().minusDays(1).toString();
//            beforeDay = 1;
//        } else if (type == 2) {
//            beforeDay = 2;
//        } else if (type == 3) {
//            beforeDay = 4;
//        } else if (type == 4) {
//            beforeDay = 30;
//        }
//
//        String startDate = LocalDate.now().minusDays(beforeDay).toString();

        MemberSourceInfo memberSourceInfo = new MemberSourceInfo();
        memberSourceInfo.setStartDateInfo(startDate);
        memberSourceInfo.setEndDateInfo(endDate);

        //List<Map<String, Object>> list1 = memberSourceInfoService.selectZhiMaList1(memberSourceInfo);

        //String number = memberSourceInfoService.selectAllZhiMaList(memberSourceInfo);

        AccountMerchantInfoHis accountMerchantInfoHis = new AccountMerchantInfoHis();
        accountMerchantInfoHis.setStartDateInfo(startDate);
        accountMerchantInfoHis.setEndDateInfo(endDate);
        String priceAmounts = accountMerchantInfoHisService.selectAccountHisAllList(accountMerchantInfoHis);

        ProductProfitInfo productProfitInfo = new ProductProfitInfo();
        productProfitInfo.setStartDateInfo(startDate);
        productProfitInfo.setEndDateInfo(endDate);
        String priceAmount = productProfitInfoService.selectProductProfitInfoList1(productProfitInfo);

        SourcePushResultInfo sourcePushResultInfo = new SourcePushResultInfo();
        sourcePushResultInfo.setStartDateInfo(startDate);
        sourcePushResultInfo.setEndDateInfo(endDate);
        String totalAmount = sourcePushResultInfoService.getTotal(sourcePushResultInfo);

        BigDecimal number = calculatePrice(priceAmounts, priceAmount, totalAmount);


        Map<String, Object> map = new HashMap<>();
        map.put("name", "总收益");
        map.put("number", number);

        List<Map<String, Object>> list1 =  new ArrayList<>();
        list1.add(0, map);

//
//        Map<String, String> map1 = new HashMap<>();
//        map1.put("zm001","无芝麻分");
//        map1.put("zm002","600分以下");
//        map1.put("zm003","600-650");
//        map1.put("zm004","650-700");
//        map1.put("zm005","700分以上");
//
//
//        for (Map<String, Object> item : list1) {
//            String zhima = (String) item.get("name");
//            if (zhima != null) {
//                String newName = map1.get(zhima);
//                if (newName != null) {
//                    item.put("name", newName);
//                }
//            }
//        }

        JSONObject returnData = new JSONObject();
        returnData.put("dataList", list1);

        return AjaxResult.success(returnData);
    }

    private BigDecimal calculatePrice(String priceAmounts, String priceAmount, String totalAmount) {
        BigDecimal amount1 = toBigDecimal(priceAmounts).orElse(BigDecimal.ZERO);
        BigDecimal amount2 = toBigDecimal(priceAmount).orElse(BigDecimal.ZERO);
        BigDecimal amount3 = toBigDecimal(totalAmount).orElse(BigDecimal.ZERO);

        return amount1.add(amount2).subtract(amount3);

    }
    private static java.util.Optional<BigDecimal> toBigDecimal(String str) {
        if (str == null || str.trim().isEmpty()) {
            return java.util.Optional.empty();
        }
        try {
            return java.util.Optional.of(new BigDecimal(str.trim()));
        } catch (NumberFormatException e) {
            return java.util.Optional.empty();
        }
    }


    /**
     * 金额消耗
     */
    @PreAuthorize("@ss.hasPermi('index:data:money')")
    @GetMapping(value = "/organizeApi")
    public AjaxResult organizeApi(@RequestParam("startDate") String startDate,
                                  @RequestParam("endDate") String endDate) {

        AccountMerchantInfoHis accountMerchantInfoHis = new AccountMerchantInfoHis();
//        String endDateInfo = LocalDate.now().toString();
//        Integer beforeDay = 0;
//        if (type == 1) {
//            endDateInfo = LocalDate.now().minusDays(1).toString();
//            beforeDay = 1;
//        } else if (type == 2) {
//            beforeDay = 2;
//        } else if (type == 3) {
//            beforeDay = 4;
//        } else if (type == 4) {
//            beforeDay = 30;
//        }
//
//        String startDate = LocalDate.now().minusDays(beforeDay).toString();
        accountMerchantInfoHis.setStartDateInfo(startDate);
        accountMerchantInfoHis.setEndDateInfo(endDate);

        List<Map<String, Object>> list = accountMerchantInfoHisService.selectAccountHisList(accountMerchantInfoHis);
        String priceAmount = accountMerchantInfoHisService.selectAccountHisAllList(accountMerchantInfoHis);
        String avgPrice = accountMerchantInfoHisService.selectAccountHisAllList1(accountMerchantInfoHis);

        Map<String, Object> map = new HashMap<>();
        map.put("name", "总消耗");
        map.put("priceAmount", priceAmount);
        map.put("avgPrice", avgPrice);

        list.add(0, map);

        JSONObject returnData = new JSONObject();
        returnData.put("apiList", list);


        return AjaxResult.success(returnData);
    }


//    @PreAuthorize("@ss.hasPermi('index:data:money')")
//    @GetMapping(value = "/organizeApi/{type}")
//    public AjaxResult organizeApi(@PathVariable("type") Integer type) {
//        String endDate = LocalDate.now().toString();
//        Integer beforeDay = 0;
//        if (type == 1) {
//            endDate = LocalDate.now().minusDays(1).toString();
//            beforeDay = 1;
//        } else if (type == 2) {
//            beforeDay = 2;
//        } else if (type == 3) {
//            beforeDay = 4;
//        } else if (type == 4){
//            beforeDay = 30;
//        }
//            String startDate = LocalDate.now().minusDays(beforeDay).toString();
//
//        // api 推送的数据
//        List<Map<String, Object>> Crmlist = merchantDataPoolInfoService.selectCrmData1(startDate, endDate);
//        List<Map<String, Object>> Apilist = merchantDataPushInfoService.selectApiData1(startDate, endDate);
//
//        Long allNumber = 0L;
//        BigDecimal allPriceAmount = BigDecimal.ZERO;
//        BigDecimal allCostAmount = BigDecimal.ZERO;
//        BigDecimal allPayAmount = BigDecimal.ZERO;
//
//        for (Map<String, Object> map : Crmlist) {
//
//            Long number = (Long) map.get("number");
//            if (ObjectUtil.isNotEmpty(number)) {
//                allNumber = allNumber + number;
//            }
//
//            BigDecimal priceAmount = (BigDecimal) map.get("priceAmount");
//            if (ObjectUtil.isNotEmpty(priceAmount)) {
//                allPriceAmount = allPriceAmount.add(priceAmount);
//            }
//
//            BigDecimal costAmount = (BigDecimal) map.get("costAmount");
//            if (ObjectUtil.isNotEmpty(costAmount)) {
//                allCostAmount = allCostAmount.add(costAmount);
//            }
//
//            BigDecimal payAmount = (BigDecimal) map.get("payAmount");
//            if (ObjectUtil.isNotEmpty(payAmount)) {
//                allPayAmount = allPayAmount.add(payAmount);
//            }
//
//            if (ObjectUtil.isAllNotEmpty(priceAmount, payAmount)) {
//                map.put("costAmount", priceAmount.subtract(payAmount));
//            }
//        }
//
//        for (Map<String, Object> map : Apilist) {
//            Long number = (Long) map.get("number");
//            if (ObjectUtil.isNotEmpty(number)) {
//                allNumber = allNumber + number;
//            }
//
//            BigDecimal priceAmount = (BigDecimal) map.get("priceAmount");
//            if (ObjectUtil.isNotEmpty(priceAmount)) {
//                allPriceAmount = allPriceAmount.add(priceAmount);
//            }
//
//            BigDecimal costAmount = (BigDecimal) map.get("costAmount");
//            if (ObjectUtil.isNotEmpty(costAmount)) {
//                allCostAmount = allCostAmount.add(costAmount);
//            }
//
//            BigDecimal payAmount = (BigDecimal) map.get("payAmount");
//            if (ObjectUtil.isNotEmpty(payAmount)) {
//                allPayAmount = allPayAmount.add(payAmount);
//            }
//
//            if (ObjectUtil.isAllNotEmpty(priceAmount, payAmount)) {
//                map.put("costAmount", priceAmount.subtract(payAmount));
//            }
//        }
//
//        List<Map<String, Object>> allDataList = new ArrayList<>();
//
//        Map<String, Object> totalMap1 = new HashMap<>();
//        totalMap1.put("name", "总消耗");
//        totalMap1.put("number", allNumber);
//        totalMap1.put("priceAmount", allPriceAmount);
//        totalMap1.put("costAmount", allPriceAmount.subtract(allPayAmount));
//        totalMap1.put("payAmount", allPayAmount);
//        allDataList.add(0, totalMap1);
//
//
//        allDataList.addAll(Crmlist);
//        allDataList.addAll(Apilist);
//
//        allDataList.sort((map1, map2) -> {
//            BigDecimal priceAmount1 = (BigDecimal) map1.get("priceAmount");
//            BigDecimal priceAmount2 = (BigDecimal) map2.get("priceAmount");
//            return priceAmount2.compareTo(priceAmount1);
//        });
//
//        JSONObject returnData = new JSONObject();
//        returnData.put("apiList", allDataList);
//
//        return AjaxResult.success(returnData);
//    }

    /**
     * 线索成本
     */
    @Autowired
    IChannelCountInfoService  channelCountInfoService;

    @PreAuthorize("@ss.hasPermi('index:data:cost')")
    @GetMapping(value = "/cost")
    public AjaxResult cost(@RequestParam("startDate") String startDate,
                           @RequestParam("endDate") String endDate,
                           @RequestParam(value = "channelCode",required= false)  String channelCode ){


        SourceDataCountInfo sourceDataCountInfo = new SourceDataCountInfo();
        sourceDataCountInfo.setStartDateInfo(startDate);
        sourceDataCountInfo.setEndDateInfo(endDate);
        sourceDataCountInfo.setChannelCode(channelCode);

        List<Map<String, Object>> list = sourceDataCountInfoService.getCpaCost(sourceDataCountInfo);

        SourcePushResultInfo sourcePushResultInfo = new SourcePushResultInfo();
        sourcePushResultInfo.setStartDateInfo(startDate);
        sourcePushResultInfo.setEndDateInfo(endDate);
        sourcePushResultInfo.setChannelCode(channelCode);
        List<Map<String, Object>> list1 = sourcePushResultInfoService.getCpsCost(sourcePushResultInfo);

        ChannelCountInfo channelCountInfo = new ChannelCountInfo();
        channelCountInfo.setChannelCode(channelCode);
        channelCountInfo.setStartDateInfo(startDate);
        channelCountInfo.setEndDateInfo(endDate);
        List<Map<String, Object>> list2 = channelCountInfoService.getUvCost(channelCountInfo);
        List<Map<String, Object>> cost3 = list2.stream()
                .filter(map -> {
                    Object cost = map.get("cost");
                    return cost != null && ((Number) cost).doubleValue() != 0;
                })
                .collect(Collectors.toList());

        // 合并两个List
        List<Map<String, Object>> allDataList = new ArrayList<>();
        allDataList.addAll(list);
        allDataList.addAll(list1);
        allDataList.addAll(cost3);

        // 累加每个条目的 cost 和 number
        BigDecimal totalCost = BigDecimal.ZERO;
        BigDecimal totalNumber = BigDecimal.ZERO;

        for (Map<String, Object> item : allDataList) {
            BigDecimal cost = new BigDecimal(item.get("cost").toString());
            BigDecimal number = new BigDecimal(item.get("number").toString());
            totalCost = totalCost.add(cost);
            totalNumber = totalNumber.add(number);
        }

        //  创建一个新的条目，表示总数量和总成本
        Map<String, Object> totalItem = new HashMap<>();
        totalItem.put("name", "总数量|成本");
        totalItem.put("cost", totalCost);
        totalItem.put("number", totalNumber);

        // 将总值条目添加到 allDataList 中
        allDataList.add(totalItem);

        // 对 allDataList 按 cost 进行排序
        allDataList.sort((map1, map2) -> {
            BigDecimal cost1 = new BigDecimal(map1.get("cost").toString());
            BigDecimal cost2 = new BigDecimal(map2.get("cost").toString());
            return cost2.compareTo(cost1);
        });

        JSONObject returnData = new JSONObject();
       returnData.put("cost", allDataList);

        return AjaxResult.success(returnData);
    }
//
//    @PreAuthorize("@ss.hasPermi('index:data:cost')")
//    @GetMapping(value = "/cost/{type}")
//    public AjaxResult cost(@PathVariable("type") Integer type) {
//        // api 推送的数据
//        List<Map<String, Object>> list = sourceDataCountInfoService.getcost(type);
//        List<Map<String, Object>> list1 = sourcePushResultInfoService.getcost(type);
//
//        // 合并两个List
//        List<Map<String, Object>> allDataList = new ArrayList<>();
//        allDataList.addAll(list);
//        allDataList.addAll(list1);
//
//        // 累加每个条目的 cost 和 number
//        BigDecimal totalCost = BigDecimal.ZERO;
//        BigDecimal totalNumber = BigDecimal.ZERO;
//
//        for (Map<String, Object> item : allDataList) {
//            BigDecimal cost = new BigDecimal(item.get("cost").toString());
//            BigDecimal number = new BigDecimal(item.get("number").toString());
//            totalCost = totalCost.add(cost);
//            totalNumber = totalNumber.add(number);
//        }
//
//        // 创建一个新的条目，表示总数量和总成本
//        Map<String, Object> totalItem = new HashMap<>();
//        totalItem.put("name", "总数量|成本");
//        totalItem.put("cost", totalCost);
//        totalItem.put("number", totalNumber);
//
//        // 将总值条目添加到 allDataList 中
//        allDataList.add(totalItem);
//
//        // 对 allDataList 按 cost 进行排序
//        allDataList.sort((map1, map2) -> {
//            BigDecimal cost1 = new BigDecimal(map1.get("cost").toString());
//            BigDecimal cost2 = new BigDecimal(map2.get("cost").toString());
//            return cost2.compareTo(cost1);  // 降序排序
//        });
//
//        JSONObject returnData = new JSONObject();
//        returnData.put("cost", allDataList);
//
//        return AjaxResult.success(returnData);
//    }


    /**
     * 表单消耗（数量+金额）
     */
    @PreAuthorize("@ss.hasPermi('index:data:xiaohao')")
    @GetMapping(value = "/push/{type}")
    public AjaxResult push(@PathVariable("type") Integer type) {
        // api 推送的数据
        List<Map<String, Object>> Crmlist = merchantDataPoolInfoService.selectCrmData(type);
        List<Map<String, Object>> Apilist = merchantDataPushInfoService.selectApiData(type);

        // 合并两个List
        List<Map<String, Object>> allDataList = new ArrayList<>();
        allDataList.addAll(Crmlist);
        allDataList.addAll(Apilist);

        // 对 allDataList 按 number 进行排序
        allDataList.sort((map1, map2) -> {
            Long number1 = (Long) map1.get("number");
            Long number2 = (Long) map2.get("number");
            return number2.compareTo(number1);  // 降序排序
        });

        JSONObject returnData = new JSONObject();
        returnData.put("allData", allDataList);

        return AjaxResult.success(returnData);
    }


    /**
     * kpi
     */
    @PreAuthorize("@ss.hasPermi('index:data:kpi')")
    @GetMapping(value = "/kpi/{type}")
    public AjaxResult kpi(@PathVariable("type") Integer type) {

        //获取月份
        YearMonth currentMonth = YearMonth.now();
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM");
        String monthly = currentMonth.format(formatter1);


        MonthlyKpiInfo monthlyKpiInfo = new MonthlyKpiInfo();
        monthlyKpiInfo.setMonthly(monthly);

        List<Map<String, Object>> list = monthlyKpiService.selectMonthlyKpiMapList(monthlyKpiInfo);

        JSONObject returnData = new JSONObject();
        returnData.put("monthlyKpiList", list);

        return AjaxResult.success(returnData);
    }


    @PreAuthorize("@ss.hasPermi('index:data:kpi')")
    @Log(title = "商户基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MonthlyKpiInfo monthlyKpiInfo) {

        //获取月份
        YearMonth currentMonth = YearMonth.now();
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM");
        String monthly = currentMonth.format(formatter1);

        monthlyKpiInfo.setMonthly(monthly);


        return AjaxResult.success(monthlyKpiService.updateMonthlyKpi(monthlyKpiInfo));
    }


    @PreAuthorize("@ss.hasPermi('index:data:moneys')")
    @GetMapping(value = "/unionAndProductList")
    public AjaxResult unionAndProductList(@RequestParam("startDate") String startDate,
                                  @RequestParam("endDate") String endDate) {

        ProductProfitInfo productProfitInfo = new ProductProfitInfo();
        productProfitInfo.setStartDateInfo(startDate);
        productProfitInfo.setEndDateInfo(endDate);

        List<Map<String, Object>> list = productProfitInfoService.selectProductProfitInfoMapList1(productProfitInfo);
        String priceAmount = productProfitInfoService.selectProductProfitInfoList1(productProfitInfo);

        Map<String, Object> map = new HashMap<>();
        map.put("name", "总消耗");
        map.put("priceAmount", priceAmount);

        list.add(0, map);

        JSONObject returnData = new JSONObject();
        returnData.put("unionAndProductList", list);


        return AjaxResult.success(returnData);
    }

    @PreAuthorize("@ss.hasPermi('index:data:user')")
    @GetMapping(value = "/authAndSourceList")
    public AjaxResult authAndSourceList(@RequestParam String startDate,
                                        @RequestParam String endDate,
                                        @RequestParam(required = false) String regAppCode) {


        List<Map<String, Object>> list = memberBaseInfoService.authAndSourceList(startDate,endDate,regAppCode);

        JSONObject returnData = new JSONObject();
        returnData.put("authAndSourceList", list);


        return AjaxResult.success(returnData);
    }

    @GetMapping(value = "/authAndSourceByWeekList")
    public AjaxResult authAndSourceByWeekList(@RequestParam String startDate,
                                        @RequestParam String endDate,
                                        @RequestParam(required = false) String regAppCode) {


        List<Map<String, Object>> list = memberBaseInfoService.authAndSourceByWeekList(startDate,endDate,regAppCode);

        JSONObject returnData = new JSONObject();
        returnData.put("authAndSourceList", list);


        return AjaxResult.success(returnData);
    }


}